package cc.site.main.controller;

import cc.site.common.utils.R;
import cc.site.main.bean.TblOrder;
import cc.site.main.bean.TblPet;
import cc.site.main.bean.vo.PetCreateVo;
import cc.site.main.service.TblOrderService;
import cc.site.main.service.TblPetService;
import cc.site.main.type.OrderType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * <p>
 * 宠物信息 前端控制器
 * </p>
 *
 * @author yangruomao
 * @since 2024-04-14
 */
@RestController
@RequestMapping("/pet")
@Api(tags = "宠物管理")
public class TblPetController {

    @Autowired
    private TblPetService petService;

    @Autowired
    private TblOrderService orderService;

    @PostMapping("/foster")
    @ApiOperation("寄养宠物。fosterHumanId 是寄养者用户ID")
    public R foster(@Valid @RequestBody(required = false) PetCreateVo vo) {

        TblPet pet = new TblPet();
        pet.setMasterHumanId(-1);
        BeanUtils.copyProperties(vo, pet);

        // 在仓库中添加宠物，然后生成订单
        if (petService.save(pet)) {
            // 生成订单
            TblOrder order = new TblOrder();
            order.setPetId(pet.getId());
            order.setUserId(vo.getFosterHumanId());
            order.setType(OrderType.Foster_Care);
            orderService.save(order);
            return R.ok().message("寄养宠物成功");
        } else {
            return R.error().message("寄养宠物失败");
        }
    }

    @PostMapping("/adoption/{userId}/{petId}")
    @ApiOperation("领养宠物")
    public R adoption(@PathVariable("userId") Integer userId,
                      @PathVariable("petId") Integer petId) {

        TblPet pet = petService.getById(petId);
        if (pet.getMasterHumanId() != -1) {
            return R.error().message("小宝贝已经被领养了，可以去联系主人哦");
        }

        pet.setMasterHumanId(userId);

        // 从仓库中删除宠物
        if (petService.updateById(pet)) {
            // 生成订单
            TblOrder order = new TblOrder();
            order.setPetId(petId);
            order.setUserId(userId);
            order.setType(OrderType.Adoption);
            orderService.save(order);
            return R.ok().message("领养成功");
        } else {
            return R.error().message("领养失败");
        }
    }

    @DeleteMapping("/{petId}")
    @ApiOperation("删除指定宠物")
    public R delete(@PathVariable("petId") Integer petId) {
        if (petService.removeById(petId)) {
            return R.ok().message("删除宠物信息成功");
        } else {
            return R.error().message("删除宠物信息失败");
        }
    }

    @PutMapping
    @ApiOperation("更新宠物信息【包含更换房间、更换种类、更换主人、更换寄养人】")
    public R update(@RequestBody TblPet pet) {
        if (petService.updateById(pet)) {
            return R.ok().message("更新宠物信息成功");
        } else {
            return R.error().message("更新宠物信息失败");
        }
    }
}
